package com.cxb;

import java.io.File;
import java.lang.reflect.Method;
import java.util.Hashtable;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amitek.aidl.mqtt.MqttServiceProxy;
import com.amitek.aidl.mqtt.bean.ConfigStatus;
import com.cxb.manager.PhoneManager;
import com.cxb.service.CXBMainService;
import com.cxb.utils.CommonUtils;
import com.cxb.utils.Debug;
import com.cxb.utils.SharedPreferencesUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

public class DeviceInfoActivity extends BaseActivity {
	private TextView tvDeviceInfo, tv_phoneNumber;
	private View rl_back;
	private Button ibGpstest, ibRecovery;
	private ImageView ivQRcode;
	private LinearLayout llySystemInfo;
	private static int QR_SIDE = 190;
	private SharedPreferencesUtils spPreferencesUtils;
	private PhoneManager mPhoneManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setting_deviceinfo);
		mPhoneManager = new PhoneManager(this);
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		init();
		super.onStart();
	}

	private String gteModelF(String model_str) {
		// if (ClientManager.WGN35.equals(model_str)) {
		// return "AMI35";
		// }
		return model_str;
	}

	private void init() {
		spPreferencesUtils = new SharedPreferencesUtils(this);
		TelephonyManager telephoneyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		tvDeviceInfo = (TextView) findViewById(R.id.tv_device_info);
		tv_phoneNumber = (TextView) findViewById(R.id.tv_phoneNumber);

		String softversion = getSystemProperties("cxb.software.version");
		if (CommonUtils.getModel().equals("YX001D")) {
			softversion = "YX001D_"
					+ getSystemProperties("cxb.software.version");
		}
		String info = getString(R.string.system_version) + "Android "
				+ getSystemProperties("ro.build.version.release") + "\r\n"
				+ getString(R.string.app_version) + softversion + "\r\n"
				+ getString(R.string.hardware_version)
				+ getSystemProperties("cxb.hardware.version") + "\r\n"
				+ getString(R.string.device_model)
				// + getSystemProperties("ro.product.model") + "\r\n"
				+ getSystemProperties("cxb.model") + "\r\n"
				+ getString(R.string.imei) + telephoneyManager.getDeviceId();

		String clientId = null;
		try {

			MqttServiceProxy mqttProxy = CXBMainService.getMqttProxy();
			if (mqttProxy != null) {
				ConfigStatus configStatus = mqttProxy.getConfigStatus();
				if (configStatus != null) {
					long deviceId = configStatus.deviceId;
					if (deviceId != 0) {
						clientId = deviceId + "";
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (!TextUtils.isEmpty(clientId)) {
			info += "\r\nClientId : " + clientId;
		}

		if (mPhoneManager.isSimCardAccess()) {
			info += "\r\n" + "ICCID : "
					+ telephoneyManager.getSimSerialNumber();
			String simPhoneNumber = telephoneyManager.getLine1Number();
			if (!TextUtils.isEmpty(simPhoneNumber)) {
				info += "\r\n" + getString(R.string.phone_number)
						+ simPhoneNumber;
			}
		}
		if (CommonUtils.getModel().equals("YX001D")) {
			info += "\r\n公司名称:陕西亿程交通信息有限公司\r\n客服电话:029-86698009\r\n地        址:陕西省西安市高新区唐延路35号旺座现代城H-1602#";
			tvDeviceInfo.setTextSize(16);
		}
		tvDeviceInfo.setText(info);
		//
		// + "\r\n"
		// + getString(R.string.phone_number)
		// + spPreferencesUtils.getLocalNumber());

		// String simPhoneNumber = telephoneyManager.getLine1Number();
		// if (!TextUtils.isEmpty(simPhoneNumber)) {
		// tv_phoneNumber.setText(simPhoneNumber);
		// } else {
		// if (new PhoneManager(this).getSIMType() ==
		// PhoneManager.SIM_CAR_TYPE_IOT) {
		// tv_phoneNumber.setText(R.string.local_number_none);
		// } else {
		// String text = spPreferencesUtils.getLocalNumber();
		// if (TextUtils.isEmpty(text)) {
		// text = getString(R.string.local_number_no_exist);
		// }
		// tv_phoneNumber.setLinkTextColor(Color.RED);
		// tv_phoneNumber.setMovementMethod(LinkMovementMethod
		// .getInstance());
		// SpannableStringBuilder style = new SpannableStringBuilder(text);
		// style.clearSpans();
		// style.setSpan(new ClickableSpan() {
		//
		// @Override
		// public void onClick(View widget) {
		// Intent intent = new Intent();
		// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		// intent.setClass(DeviceInfoActivity.this,
		// SettingNumberActivity.class);
		// startActivity(intent);
		//
		// }
		// }, 0, text.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
		//
		// tv_phoneNumber.setText(style);
		// }
		// }
		ibGpstest = (Button) findViewById(R.id.ib_gps_info);
		rl_back = findViewById(R.id.rl_back);
		rl_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		ibGpstest.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				startActivity(new Intent(DeviceInfoActivity.this,
						GpsTestActivity.class)
						.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP));
			}
		});

		ibRecovery = (Button) findViewById(R.id.ib_reset);
		ibRecovery.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				AlertDialog.Builder builder = new Builder(
						DeviceInfoActivity.this);
				builder.setMessage(R.string.recovery);
				builder.setTitle(R.string.prompt);
				builder.setPositiveButton(R.string.confirm,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								recovery();
								dialog.dismiss();
							}
						});
				builder.setNegativeButton(R.string.cancel,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						});
				builder.create().show();
			}
		});

		llySystemInfo = (LinearLayout) findViewById(R.id.lly_system_info);
		ivQRcode = (ImageView) findViewById(R.id.iv_qrcode);
		createImage(tvDeviceInfo.getText() + "");
		ivQRcode.setVisibility(View.GONE);
	}

	private void recovery() {

		sendBroadcast(new Intent("android.intent.action.MASTER_CLEAR"));

	}

	private static boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			// 递归删除目录中的子目录下
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}
		// 目录此时为空，可以删除
		return dir.delete();
	}

	/**
	 * @MethodName: getSystemProperties
	 * @Description: ��ȡϵͳ����
	 * @author ������
	 * @date 2013-9-7
	 * 
	 */
	private String getSystemProperties(String field)// ȡϵͳ����
	{
		String platform = null;
		try {
			Class<?> classType = Class.forName("android.os.SystemProperties");
			Method getMethod = classType.getDeclaredMethod("get",
					new Class<?>[] { String.class });
			platform = (String) getMethod.invoke(classType,
					new Object[] { field });
		} catch (Exception e) {
			e.printStackTrace();
		}
		return platform;
	}

	// ���QRͼ
	private void createImage(String text) {
		try {
			if (text == null || "".equals(text) || text.length() < 1) {
				return;
			}
			Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
			BitMatrix bitMatrix = new QRCodeWriter().encode(text,
					BarcodeFormat.QR_CODE, QR_SIDE, QR_SIDE, hints);
			int[] pixels = new int[QR_SIDE * QR_SIDE];
			for (int y = 0; y < QR_SIDE; y++) {
				for (int x = 0; x < QR_SIDE; x++) {
					if (bitMatrix.get(x, y)) {
						pixels[y * QR_SIDE + x] = 0xff000000;
					} else {
						pixels[y * QR_SIDE + x] = 0xffffffff;
					}

				}
			}

			Bitmap bitmap = Bitmap.createBitmap(QR_SIDE, QR_SIDE,
					Bitmap.Config.ARGB_8888);

			bitmap.setPixels(pixels, 0, QR_SIDE, 0, 0, QR_SIDE, QR_SIDE);
			ivQRcode.setImageBitmap(bitmap);

		} catch (WriterException e) {
			e.printStackTrace();
		}
	}

	// private String getSoftWareVersion() {
	// String sVersion = null;
	// try {
	// SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	// sVersion = date.format(getPackageManager().getPackageInfo(
	// this.getPackageName(), 0).lastUpdateTime);
	// } catch (Exception e) {
	// sVersion = "unknown";
	// e.printStackTrace();
	// }
	// return sVersion;
	// }

	int count = 0;
	int development_count = 0;

	public boolean onTouchEvent(android.view.MotionEvent event) {

		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			if (event.getX() > 400 && event.getY() < 140) {
				count++;
				development_count = 0;
			} else if (event.getX() < 70 && event.getY() < 140) {
				development_count++;
				count = 0;
			} else {
				development_count = 0;
				count = 0;
			}

			Debug.printf("test", "count=" + count);
			if (count >= 6) {
				// Intent intent = new Intent(
				// Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS);
				// startActivity(intent);
				Intent intent = new Intent();
				intent.setClassName("com.zzx.factorytest",
						"com.zzx.factorytest.MainActivity");
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);

				count = 0;
			} else if (development_count >= 6) {
				Settings.Secure.putInt(getContentResolver(),
						Settings.Secure.ADB_ENABLED, 1);
				Toast.makeText(this, R.string.open_development_mode_success,
						Toast.LENGTH_SHORT).show();
				development_count = 0;
			}
		}
		return false;

	};
}
